package com.atguigu.gmall.list.receiver;

import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.list.servcie.SearchService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ListReceiver {

    @Autowired
    private SearchService searchService;

    /**
     * 商品上架
     *
     * @param skuId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_UPPER),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_UPPER}
    ))
    public void upload(Long skuId, Message message, Channel channel) {

        try {
            if (skuId != null) {
    //            获取状态码
                long deliveryTag = message.getMessageProperties().getDeliveryTag();
                channel.basicAck(deliveryTag, false);

//                商品上架
                searchService.uploadEs(skuId);
            }
        } catch (IOException e) {
            e.printStackTrace();
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
//            第三个false是否重返队列
            channel.basicNack(deliveryTag, false,false);
        }
    }


    /**
     * 商品下架
     *
     * @param skuId
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_GOODS_LOWER),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_GOODS),
            key = {MqConst.ROUTING_GOODS_LOWER}
    ))
    public void lower(Long skuId, Message message, Channel channel) {

        try {
            if (skuId != null) {
                //            获取状态码
                long deliveryTag = message.getMessageProperties().getDeliveryTag();
                channel.basicAck(deliveryTag, false);

//                商品上架
                searchService.deleteEs(skuId);
            }
        } catch (IOException e) {
            e.printStackTrace();
            long deliveryTag = message.getMessageProperties().getDeliveryTag();
//            第三个false是否重返队列
            channel.basicNack(deliveryTag, false,false);
        }
    }
}
